package cn.lf.android.lawfirm.home;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.lf.android.lawfirm.AppConfig;
import cn.lf.android.lawfirm.BaseActivity;
import cn.lf.android.lawfirm.R;
import cn.lf.android.lawfirm.conflict.ConflictListActivity;
import cn.lf.android.lawfirm.conflict.ConflictSearchListActivity;
import cn.lf.android.lawfirm.home.controller.EditionController;
import cn.lf.android.lawfirm.home.controller.HomeController;
import cn.lf.android.lawfirm.home.controller.MessageController;
import cn.lf.android.lawfirm.home.controller.QuitController;
import cn.lf.android.lawfirm.home.controller.UserInfoController;
import cn.lf.android.lawfirm.home.modle.HomeGroups;
import cn.lf.android.lawfirm.home.modle.Message;
import cn.lf.android.lawfirm.home.modle.UserInfo;
import cn.lf.android.lawfirm.home.view.HomeAdapter;
import cn.lf.android.lawfirm.inputsource.InputSourceActivity;
import cn.lf.android.lawfirm.login.LoginActivity;
import cn.lf.android.lawfirm.notice.NoticeListActivity;
import cn.lf.android.lawfirm.outgoingregistration.AddOutGoingActivity;
import cn.lf.android.lawfirm.outgoingregistration.OutGoingRegistrationActivity;
import cn.lf.android.lawfirm.undertake.apply.ApplyUndertakeActivity;
import cn.lf.android.lawfirm.utils.DebugLog;
import cn.lf.android.lawfirm.utils.SPUtil;
import cn.lf.android.lawfirm.view.AutoTextView;
import cn.lf.android.lawfirm.view.MyGridView;
import cn.lf.android.lawfirm.view.OptionDialog;
import cn.lf.android.lawfirm.worklog.AddWorkLogActivity;
import cn.lf.android.lawfirm.worklog.WorkLogListActivity;

import static android.R.id.list;
import static cn.lf.android.lawfirm.MyApplication.context;

public class HomeActivity extends BaseActivity implements HomeController.HomeCallback, MessageController.MessageCallback, QuitController.QuitCallback, UserInfoController.UserInfoCallback, EditionController.EditionCallback {
    private Handler handler = new Handler();
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            // handler自带方法实现定时器
            try {
                handler.postDelayed(this, 5000);
                autoTextView.next();
                autoTextView.setText(arrList.get(count % arrList.size()));
                count++;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
    private int count = 0;
    private List<String> arrList = new ArrayList<String>();
    private MyGridView home_gridview;
    private AutoTextView autoTextView;
    private TextView jod, message;
    private ImageView mInputSource, img_worklog;
    private HomeAdapter mHomeAdapter;
    List<HomeGroups> groupsList = new ArrayList<HomeGroups>();
    private HomeController mHomeController;
    private MessageController mMessageController;
    private TextView quit;
    private QuitController mQuitController;
    private ImageView mOutGoing;
    private RelativeLayout search;
    private UserInfoController mUserInfoController;
    private EditionController mEditionController;

    @Override
    public Object getContentResView() {
        return R.layout.activity_home;
    }

    @Override
    public void initView() {
        autoTextView = (AutoTextView) findViewById(R.id.autoTextView);
        home_gridview = (MyGridView) findViewById(R.id.home_gridview);
        mInputSource = ((ImageView) findViewById(R.id.img_inputSource));
        mOutGoing = ((ImageView) findViewById(R.id.img_outgoing));
        img_worklog = ((ImageView) findViewById(R.id.img_worklog));
        search = ((RelativeLayout) findViewById(R.id.search));
        search.setOnClickListener(this);
        mOutGoing.setOnClickListener(this);
        mInputSource.setOnClickListener(this);
        img_worklog.setOnClickListener(this);
        jod = (TextView) findViewById(R.id.jod);
        jod.setOnClickListener(this);
        message = (TextView) findViewById(R.id.message);
        message.setOnClickListener(this);
        mHomeAdapter = new HomeAdapter(HomeActivity.this, groupsList);
        home_gridview.setAdapter(mHomeAdapter);
        quit = ((TextView) findViewById(R.id.quit));
        quit.setOnClickListener(this);
        quit.setVisibility(View.GONE);
    }

    @Override
    public void initData() {
        mHomeController = new HomeController(this, this);
        mMessageController = new MessageController(this, this);
        mUserInfoController = new UserInfoController(this, this);
        mEditionController = new EditionController(this, this);
        mHomeController.onHome();
        mEditionController.onEdition();
        handler.postDelayed(runnable, 0);
        onCheckQuanxian();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search:
                Intent intent2 = new Intent(this, ConflictSearchListActivity.class);
                startActivity(intent2);
                break;
            case R.id.quit:
                onQuit();
                break;
            case R.id.img_worklog:
                Intent intent = new Intent(this, WorkLogListActivity.class);
                intent.putExtra("title", "工作日志");
                intent.putExtra("flag", "0");//日志查阅 传1  工作日志传0
                startActivity(intent);
                break;
            case R.id.jod:
//                Intent intent = new Intent(this, WorkLogListActivity.class);
//                startActivity(intent);
                break;
            case R.id.message:
                Intent intent3 = new Intent(this, NoticeListActivity.class);
                startActivity(intent3);
                break;
            case R.id.img_inputSource:
                startActivity(new Intent(this, InputSourceActivity.class));
                break;
            case R.id.img_outgoing:
                //外出登记
                Intent intent4 = new Intent(this, AddOutGoingActivity.class);
                intent4.putExtra("type", "添加外出登记");
                startActivity(intent4);
                break;
            default:
                break;
        }
    }

    @Override
    public void onSuccessed(List<HomeGroups> beans) {
        groupsList.addAll(beans);
        DebugLog.e("beans==" + beans);
        for (int i = 0; i < beans.size(); i++) {
            if (beans.get(i).getMenuID() == 8) {
                groupsList.remove(i);
            }
        }
        HomeGroups out = new HomeGroups();
        out.setMenuID(13);
        out.setMenumName("退出");
        groupsList.add(out);
        mHomeAdapter.notifyDataSetChanged();
        mUserInfoController.onUserInfo();

    }

    public void onQuit() {
        if (null == mQuitController) {
            mQuitController = new QuitController(this, this);
        }
        mQuitController.onQuit();
    }

    @Override
    public void onFailed() {

    }

    List<Message> mbeans = new ArrayList<>();

    @Override
    public void onMeaasgeSuccessed(List<Message> beans) {
        mbeans.addAll(beans);
        for (Message bean : beans) {
            arrList.add(bean.subTitle);
        }
    }

    @Override
    public void onMessageFailed() {

    }

    @Override
    public void onQuitSuccessed(String u) {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.putExtra("username", u);
        startActivity(intent);
        finish();
    }

    @Override
    public void onQuitFailed() {
        showCToast("操所失败");
    }

    @Override
    public void onUserInfoSuccessed(UserInfo beans) {
        mMessageController.onMessage("1", "notYet");
    }

    @Override
    public void onUserInfoFailed() {

    }

    @Override
    public void onEditionSuccessed(String beans) {

        if (!beans.equals(AppConfig.EditionNUM)) {
            if (beans.length() > 0) {
                String old = AppConfig.EditionNUM.replace(".", "");
                int oldi = Integer.valueOf(old);
                String xin = beans.replace(".", "");
                int xini = Integer.valueOf(xin);
                if (xini > oldi) {
                    giveUpShow("新版本已上线，请及时更新");
                }
            }
        }
    }

    @Override
    public void onEditionFailed() {

    }

    /**
     * 更新提示
     */
    private void giveUpShow(String str) {
        final OptionDialog dialog = new OptionDialog(this);
        dialog.setAnimationEnable(true);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_promess,
                null);
        TextView promess = (TextView) view.findViewById(R.id.promess);
        promess.setText(str);
        dialog.setPositiveListener("确定", new OptionDialog.OnPositiveListener() {
            @Override
            public void onClick(OptionDialog dialog) {
                dialog.optionDialogDismiss();
                dialog.dismiss();
            }
        });
        dialog.setCustomView(view);
        dialog.show();
    }

    private void onCheckQuanxian() {
        if (Build.VERSION.SDK_INT >= 23) {// 判断版本
            if (ContextCompat.checkSelfPermission(
                    HomeActivity.this,
                    Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(mActivity,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat
                        .requestPermissions(
                                HomeActivity.this,
                                new String[]{
                                        Manifest.permission.READ_EXTERNAL_STORAGE,
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                8);
            } else {
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
//                    startActivityForResult(intent1, SELECT);
                } else {
//                    startActivityForResult(intent1, SELECT);
                }
            }

        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                startActivityForResult(intent1, SELECT);
            } else {
//                startActivityForResult(intent1, SELECT);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {
        if (requestCode == 8) {// 读取文件
            if (grantResults[0] == 0) {// 允许
                Intent intent1 = new Intent(Intent.ACTION_GET_CONTENT);
                intent1.setType("application/msword");//application/msword
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                } else {
                }
            } else {// 拒绝
//                if (!shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)
//                        || !shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//                giveUpShow("读取文件失败，请检查设备并开启权限");
//                }
            }
        }
    }

//    /**
//     * 权限拒绝显示
//     */
//    private void giveUpShow(String str) {
//        final OptionDialog dialog = new OptionDialog(this);
//        dialog.setAnimationEnable(true);
//        View view = LayoutInflater.from(this).inflate(R.layout.dialog_promess,
//                null);
//        TextView promess = (TextView) view.findViewById(R.id.promess);
//        promess.setText(str);
//        dialog.setPositiveListener("确定", new OptionDialog.OnPositiveListener() {
//            @Override
//            public void onClick(OptionDialog dialog) {
//                dialog.optionDialogDismiss();
//                dialog.dismiss();
//            }
//        });
//        dialog.setCustomView(view);
//        dialog.show();
//    }
}
